package it.desertsupport.hibernate.dao;

import it.desertsupport.model.User;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Restrictions;

public class UserDAOImpl extends BaseHibernateDAO implements UserDAO {

	@Override
	public void save(User user) throws Exception {
		getSession().save(user);
	}

	@Override
	public void delete(User user) throws Exception {
		getSession().delete(user);
	}

	@Override
	public User getUser(Long id) throws Exception {
		return (User) getSession().get(User.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findAll() throws Exception {
		String queryString = "from User";
		Query queryObject = getSession().createQuery(queryString);
		return queryObject.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> findByExample(User user) throws Exception {
		Criteria cri = getSession().createCriteria(User.class);
		cri.add(Example.create(user));
		return cri.list();
	}

	@Override
	public User login(String userName, String password) throws Exception {
		Criteria cri = getSession().createCriteria(User.class);
		cri.add(Restrictions.eq("userName", userName));
		cri.add(Restrictions.eq("password", password));
		cri.add(Restrictions.eq("activated", "YES"));
		return (User) cri.uniqueResult();
	}
	
	@Override
	public User marge(User user) throws Exception {
		return (User) getSession().merge(user);
	}

}
